package com.sky.controller.user;


import com.sky.constant.JwtClaimsConstant;
//jwt令牌用于登录校验 可设置过期时间
import com.sky.dto.UserLoginDTO;
//接收前端传过来的数据
import com.sky.entity.User;
import com.sky.properties.JwtProperties;
//jwt令牌属性类
import com.sky.result.Result;
//用于返回
import com.sky.service.UserService;
import com.sky.utils.JwtUtil;
//令牌的工具类 可用于解析令牌或生成令牌等
import com.sky.vo.UserLoginVO;
//用于返回前端数据
import io.swagger.annotations.Api;
//接口文档
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;


@RestController
@RequestMapping("/user/user")
@Slf4j
@Api(tags = "C端用户相关接口")
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private JwtProperties jwtProperties;

    //定义一个方法名叫login的controller方法
    @PostMapping("/login")
    @ApiOperation("微信登录")
    public Result<UserLoginVO> login(@RequestBody UserLoginDTO userLoginDTO){
        log.info("微信用户登录：{}",userLoginDTO.getCode());

        //微信登录
        User user = userService.wxLogin(userLoginDTO);
        //调用service登录

        //为微信用户生成jwt令牌
        Map<String, Object> claims = new HashMap<>();
        claims.put(JwtClaimsConstant.USER_ID,user.getId());
        String token = JwtUtil.createJWT(jwtProperties.getUserSecretKey(), jwtProperties.getUserTtl(), claims);


        UserLoginVO userLoginVO = UserLoginVO.builder()
                .id(user.getId())
                .openid(user.getOpenid())
                .token(token)
                .build();

        return Result.success(userLoginVO);

    }

}
